import { Button, Input, message, Table, Tag, Upload } from 'antd';
import React, { useState, useEffect, useMemo } from 'react';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Modal, Form, DatePicker, Select } from 'antd';
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';
import api from '../../utils/api';
import { People } from '@prisma/client';
// 使用 Prisma 生成的 People 类型，并可选地扩展它
type PeopleData = People;

// 定义列元数据类型
interface ColumnMetadata {
  name: string;
  displayName: string;
  width?: number;
  sortable?: boolean;
  required?: boolean;
  type?: string;
}

const List: React.FC = () => {
    const [peopleData, setPeopleData] = useState<PeopleData[]>([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [currentRecord, setCurrentRecord] = useState<PeopleData | null>(null);
    const [searchValue, setSearchValue] = useState('');
    const [total, setTotal] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(8);
    const [columnMetadata, setColumnMetadata] = useState<ColumnMetadata[]>([]);
    
    const fetchPeopleData = async () => {
        try {
            setLoading(true);
            const response = await api.post('/people/search', {
                page: currentPage,
                pageSize,
                searchValue
            });
            setPeopleData(response.data.data || []);
            setTotal(response.data.total || 0);
        } catch (error) {
            console.error('获取人员数据失败:', error);
            message.error('获取人员数据失败');
        } finally {
            setLoading(false);
        }
    };
    
    useEffect(() => {
        fetchPeopleData();
    }, [currentPage, pageSize, searchValue]);
    
    const handleSearch = (value: string) => {
        setSearchValue(value);
        setCurrentPage(1);
    };
    
    const handleDelete = async (id: number) => {
        try {
            await api.delete(`/people/${id}`);
            message.success('删除成功');
            const sData = peopleData.filter(item => item.id !== id);
            if(sData.length === 0&&currentPage>1){
                setCurrentPage(currentPage-1);
            }else{
                fetchPeopleData();
            }
        } catch (error) {
            console.error('删除失败:', error);
            message.error('删除失败');
        }
    };
    
    const handleFormSubmit = async () => {
        try {
            const values = await form.validateFields();
            const processedValues = {
                ...values,
                birthDate: values.birthDate.format('YYYY-MM-DD'),
                employmentDate: values.employmentDate.format('YYYY-MM-DD')
            };
            
            if (currentRecord) {
                await api.put(`/people/${currentRecord.id}`, processedValues);
                message.success('修改成功！');
            } else {
                await api.post('/people', processedValues);
                message.success('新增成功！');
            }
            
            setIsModalVisible(false);
            form.resetFields();
            fetchPeopleData();
        } catch (error) {
            console.error('提交失败:', error);
            message.error('验证失败: 请检查所有必填项');
        }
    };
    
    const handleExportExcel = () => {
        try {
            const exportColumns = columnMetadata
                .filter(col => col.name && col.name !== '操作')
                .map(col => ({
                    title: col.displayName,
                    dataIndex: col.name
                }));
            const exportData = peopleData.map(record => {
                const rowData: Record<string, any> = {};
                exportColumns.forEach(col => {
                    let value = record[col.dataIndex as keyof typeof record];
                    
                    if (col.dataIndex === 'status') {
                        value = record.status;
                    }
                    
                    rowData[col.title] = value;
                });
                if (record.contact) {
                    rowData['联系方式'] = record.contact;
                }
                return rowData;
            });

            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.json_to_sheet(exportData);
            
            const colWidths = exportColumns.map(() => ({ wch: 15 }));
            ws['!cols'] = colWidths;

            XLSX.utils.book_append_sheet(wb, ws, '人员信息表');
            XLSX.writeFile(wb, `人员信息表_${dayjs().format('YYYY-MM-DD')}.xlsx`);
            message.success('导出成功！');
        } catch (error) {
            message.error('导出失败，请重试！');
            console.error('导出错误：', error);
        }
    };
    //导入excel
    const handleImportExcel = (file: File) => {
        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const data = new Uint8Array(e.target?.result as ArrayBuffer);
                const workbook = XLSX.read(data, { type: 'array' });
                const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                const jsonData = XLSX.utils.sheet_to_json(worksheet);
                
                const importPromises = jsonData.map(async (row: any) => {
                    const personData = {
                        name: row['姓名'] || '',
                        gender: row['性别'] || '男',
                        birthDate: row['出生日期'] || '',
                        hometown: row['籍贯'] || '',
                        rank: row['职位'] || '',
                        unit: row['部门'] || '',
                        status: row['状态'] || '在职',
                        employmentDate: row['入职日期'] || '',
                        contact: row['联系方式'],
                        score: row['成绩'] ? parseInt(row['成绩']) : null
                    };
                    
                    return api.post('/people', personData);
                });
                
                await Promise.all(importPromises);
                message.success(`成功导入 ${jsonData.length} 条数据`);
                fetchPeopleData();
            } catch (error) {
                message.error('导入失败，请检查文件格式是否正确');
                console.error('导入错误：', error);
            }
        };
        reader.readAsArrayBuffer(file);
        return false;
    };
    
    // 获取表结构
    const fetchTableStructure = async () => {
        try {
            const response = await api.get('/people/metadata');
            setColumnMetadata(response.data);
        } catch (error) {
            console.error('获取表格元数据失败:', error);
            message.error('获取表格元数据失败');
        }
    };
    
    useEffect(() => {
        fetchTableStructure();
    }, []);
    
    // 生成最终的表格列配置
    const columns = useMemo(() => {
        const generatedColumns = columnMetadata.map(meta => {
            const column: any = {
                title: meta.displayName,
                dataIndex: meta.name,
                width: meta.width,
                sortable: meta.sortable
            };
            
            // 添加特殊字段的自定义渲染器
            if (meta.name === 'name') {
                column.render = (text: string) => <span className="font-medium">{text}</span>;
            } else if (meta.name === 'status') {
                column.render = (status: string) => (
                    <Tag color={status === '在职' ? 'green' : 'red'} className="rounded-full">
                        {status}
                    </Tag>
                );
            }
            
            return column;
        });
        
        // 添加操作列
        generatedColumns.push({
            title: '操作',
            width: 120,
            render: (_: any, record: PeopleData) => (
                <div className="flex space-x-2">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        className="text-blue-500 hover:text-blue-700"
                        onClick={() => {
                            setCurrentRecord(record);
                            form.setFieldsValue({
                                ...record,
                                birthDate: dayjs(record.birthDate),
                                employmentDate: dayjs(record.employmentDate)
                            });
                            setIsModalVisible(true);
                        }}
                    />
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record.id)}
                    />
                </div>
            )
        });
        
        return generatedColumns;
    }, [columnMetadata, form]);

    return (
        <div className="p-6 bg-white rounded-lg shadow-sm">
            <div className="mb-6 flex justify-between items-center">
                <h2 className="text-2xl font-semibold text-gray-800 min-w-[200px]">人员信息管理</h2>
                <Input.Search
                    placeholder="根据姓名或部门搜索"
                    className="w-full md:w-64 rounded-lg border-gray-300"
                    onChange={e => setSearchValue(e.target.value)}
                    onSearch={handleSearch}
                />
                <Upload
                    accept=".xlsx,.xls"
                    showUploadList={false}
                    beforeUpload={handleImportExcel}
                >
                    <Button
                        type="primary"
                        className="bg-green-600 hover:bg-green-700 h-10 px-6 flex items-center w-full md:w-auto mr-2"
                    >
                        导入Excel
                    </Button>
                </Upload>
                <Button
                    type="primary"
                    className="bg-blue-600 hover:bg-blue-700 h-10 px-6 flex items-center w-full md:w-auto"
                    onClick={handleExportExcel}
                >
                    导出Excel
                </Button>
                <Button
                    type="primary"
                    className="bg-blue-600 hover:bg-blue-700 h-10 px-6 flex items-center w-full md:w-auto"
                    onClick={() => {
                        setCurrentRecord(null);
                        form.resetFields();
                        setIsModalVisible(true);
                    }}
                >
                    + 添加人员
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={peopleData.map(item => ({ ...item, key: item.id }))}
                pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    total: total,
                    onChange: (page, size) => {
                        setCurrentPage(page);
                        setPageSize(size || 8);
                    }
                }}
                loading={loading}
                bordered
                scroll={{ x: 1200 }}
                rowClassName="hover:bg-gray-50 transition-colors"
                className="rounded-lg overflow-hidden border border-gray-200"
            />
            
            <Modal
                title={currentRecord ? "编辑人员信息" : "新增人员"}
                open={isModalVisible}
                onOk={handleFormSubmit}
                onCancel={() => setIsModalVisible(false)}
                cancelText="取消"
                okText="提交"
            >
                <Form form={form} layout="vertical">
                    <Form.Item label="姓名" name="name" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="性别" name="gender" rules={[{ required: true }]}>
                        <Select>
                            <Select.Option value="男">男</Select.Option>
                            <Select.Option value="女">女</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="出生日期" name="birthDate" rules={[{ required: true }]}>
                        <DatePicker />
                    </Form.Item>
                    <Form.Item label="籍贯" name="hometown" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="职位" name="rank" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="部门" name="unit" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="入职日期" name="employmentDate" rules={[{ required: true }]}>
                        <DatePicker />
                    </Form.Item>
                    <Form.Item label="状态" name="status" rules={[{ required: true }]}>
                        <Select>
                            <Select.Option value="在职">在职</Select.Option>
                            <Select.Option value="离职">离职</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="联系方式" name="contact">
                        <Input />
                    </Form.Item>
                    <Form.Item label="成绩" name="score">
                        <Input type="number" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default List;